package org.chengn.level_middle.context2182;

/**
 * @Title: Context2180
 * @Author ChengN
 * @Package org.chengn.level_middle.context2182
 * @Date 2024/1/13 12:11
 * @description: 构造限制重复的字符串
 */
public class Context2182 {
    public String repeatLimitedString(String s, int repeatLimit) {
        int[] ans = new int[26];
        for (char c : s.toCharArray()) {
            ans[(int)c - 'a'] ++;
        }

        int repeat = 0;
        int lastIdx = -1;
        StringBuilder res = new StringBuilder();
        while (true) {
            int idx = -1;
            for (int i = 25; i >= 0; --i) {
                if (ans[i] == 0 || repeat == repeatLimit && i == lastIdx) continue;
                if (i != lastIdx) repeat = 0;
                idx = i;
                repeat++;
                break;
            }

            if (idx == -1) break;
            lastIdx = idx;
            ans[idx]--;
            res.append((char)(idx + (int)'a'));

        }
        return res.toString();

    }
}
